package com.seu.me.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * Created by liangfeihu on 2018/8/29.
 */
public class MethodTest {

    /**
     * 不包含继承类里面的方法：
     * - getMethods(): 获得类的public类型的方法
     * - getMethod(String name, Class[] params): 获得类的特定方法,name参数指定方法的名字,params参数指定方法的参数类型
     * - getDeclaredMethods(): 获取类中所有的方法(public、protected、default、private)
     * - getDeclaredMethod(String name, Class[] params): 获得类的特定方法,name参数指定方法的名字,params参数指定方法的参数类型
     */
    public static void main(String[] args) throws Exception {
        //使用反射第一步:获取操作类MethodDemoFieldDemo所对应的Class对象
        Class<?> cls = Class.forName("com.seu.me.reflect.MethodDemo");
        //使用MethodDemo类的class对象生成 实例
        Object obj = cls.newInstance();

        //获取public int addResult(int addNum)方法
        Method addMethod = cls.getMethod("addResult", new Class[]{int.class});
        System.out.println("修饰符: " + Modifier.toString(addMethod.getModifiers()));
        System.out.println("返回值: " + addMethod.getReturnType());
        System.out.println("方法名称: " + addMethod.getName());
        System.out.println("参数列表: " + addMethod.getParameterTypes());
        int result = (int) addMethod.invoke(obj, 2);
        System.out.println("调用addResult后的运行结果:" + result);

        System.out.println("--------------------------------");

        //获取public String toString() 方法
        Method toStringMethod = cls.getMethod("toString", new Class[]{});
        System.out.println("修饰符: " + Modifier.toString(toStringMethod.getModifiers()));
        System.out.println("返回值: " + toStringMethod.getReturnType());
        System.out.println("方法名称: " + toStringMethod.getName());
        System.out.println("参数列表: " + toStringMethod.getParameterTypes());
        String msg = (String) toStringMethod.invoke(obj);
        System.out.println("调用toString后的运行结果:" + msg);

        System.out.println("--------------------------------");

        Method[] methods = cls.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println(method);
        }

        System.out.println("--------------------------------");

        Constructor<?>[] declaredConstructors = cls.getDeclaredConstructors();
        for (Constructor<?> constructor : declaredConstructors) {
            System.out.println(constructor);
        }

        System.out.println("--------------------------------");
        Method testMethod = cls.getDeclaredMethod("test");
        System.out.println("修饰符: " + Modifier.toString(testMethod.getModifiers()));
        System.out.println("返回值: " + testMethod.getReturnType());
        System.out.println("返回值2: " + testMethod.getGenericReturnType());
        System.out.println("方法名称: " + testMethod.getName());
        System.out.println("参数列表: " + testMethod.getParameterTypes());
    }

}
